﻿using System;

namespace FrameWork
{
    /// <summary>
    /// 模型模块
    /// </summary>
    public abstract class BaseModule
    {

        public enum EnumRegisterMode
        {
            NotRegister,
            AutoRegister,
            AlreadyRegister,
        }

        private EnumObjectState state = EnumObjectState.Init;

        public event StateChangeEvent StateChanged;

        public EnumObjectState State
        {
            get
            {
                return state;
            }
            set
            {
                if (state == value) return;
                EnumObjectState oldState = state;
                state = value;

                if (null != StateChanged)
                    StateChanged(this,state,oldState);
                OnStateChange(state,oldState);
            }
        }

        protected virtual void OnStateChange(EnumObjectState newState,EnumObjectState oldState)
        {

        }

        public EnumRegisterMode regieterMode = EnumRegisterMode.NotRegister;

        //判读是否需要自动注册
        public bool AutoRegister
        {
            get
            {
                return regieterMode == EnumRegisterMode.NotRegister ? false : true;
            }
            set
            {
                if (regieterMode == EnumRegisterMode.NotRegister || regieterMode == EnumRegisterMode.AutoRegister)
                {
                    regieterMode = value ? EnumRegisterMode.AutoRegister : EnumRegisterMode.NotRegister;
                }
            }
        }

        public bool HasRegistered
        {
            get
            {
                return regieterMode == EnumRegisterMode.AlreadyRegister;
            }
        }

        public void Release()
        {
            if (State != EnumObjectState.Disabled)
            {
                State = EnumObjectState.Disabled;

                //

                if (regieterMode == EnumRegisterMode.AlreadyRegister)
                {
                    //反注册

                    regieterMode = EnumRegisterMode.AutoRegister;
                }

                OnRelease();

            }

        }

        public void Load()
        {
            if (State != EnumObjectState.Init) return;

            State = EnumObjectState.loading;

            //load 模块注册

            if (regieterMode == EnumRegisterMode.AutoRegister)
            {
                //自动注册

                regieterMode = EnumRegisterMode.AlreadyRegister;
            }

            OnLoad();

            State = EnumObjectState.Ready;
        }

        protected virtual void OnLoad()
        {

        }

        protected void OnRelease()
        {

        }

        public BaseModule()
        {

        }




    }
}
